package com.kgc.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.kgc.common.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
public class FilesOssDemoController {
    //1.先创建获取OSS的密钥和地址还有仓库名称
    private static final String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tKTsvu252YxN63nTnty";
    private static final String accessKeySecret = "MOEcB7pkBxpCODSq2WlRaCjY0DSBCG";
    private static final String bucketName = "wangkaixiang";


    //创建方法upload
    public String upload(MultipartFile imageFile) throws IOException {
        // 获取上传文件的输入流
        InputStream inputStream = imageFile.getInputStream();

        // 获取上传文件的原始名称
        String originalFilename = imageFile.getOriginalFilename();

        // 生成新的文件名，使用 UUID 作为前缀，保留原文件扩展名
        String uuID = UUID.randomUUID().toString();
        String fileName = uuID + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建阿里云 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建 PutObjectRequest 对象，指定上传到 OSS 的存储桶名、文件名及上传的本地文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, originalFilename, new File(fileName));

        // 执行文件上传操作
        ossClient.putObject(bucketName, fileName, inputStream);

        // 构建上传后的文件访问 URL，基于 endpoint、bucketName 和新文件名
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        // 关闭 OSS 客户端，释放资源
        ossClient.shutdown();

        // 返回上传到 OSS 后的文件访问 URL
        return url;
    }
}
